package model.factories.controlflow;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;
import model.Interpreter;
import model.SyntaxErrorException;
import model.commands.Command;
import model.commands.controlflow.ListCommand;
import model.factories.CommandFactory;


/**
 * A factory used to build BracketCommand objects
 * 
 * @author Erick Gonzalez
 * @author JLongley
 */
public class ListCommandFactory extends CommandFactory {
    
    private static final String CLOSE_BRACKET = "]";
    private final Pattern myBracketPattern = Pattern.compile("\\[");

    /**
     * 
     * @param interpreter an Interpreter
     */
    public ListCommandFactory (Interpreter interpreter) {
        super(interpreter);
    }

    @Override
    public Command createCommand (Scanner commandReader,
                                  Map<String, Integer> variables) throws SyntaxErrorException {
        Interpreter interpreter = getInterpreter();

        // define new variable scope. every command in this part of the tree
        // downward will this map until the next bracket is reached.
        // only the top level map is preserved from call to call (global scope)
        Map<String, Integer> newVariables = new HashMap<String, Integer>(variables);

        Command myCommand = new ListCommand();
        // read the open bracket
        commandReader.next();

        // while there isn't a closing bracket next
        while (!commandReader.hasNext(CLOSE_BRACKET)) {
            Command arg = interpreter.parse(commandReader, newVariables);
            myCommand.getArguments().add(arg);
        }

        // remove the extra close bracket
        commandReader.next();
        return myCommand;
    }

    @Override
    public Pattern patternToMatch () {
        return myBracketPattern;
    }
}
